package com.safe.utils;

import java.io.*;
import java.util.Map;

/**
 * 文本文件操作工具类
 * Created by Administrator on 2020/5/19.
 */
public class TxtUtil {

    /**
     * 读取txt文件的内容
     *
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader streamReader = new InputStreamReader(fileInputStream, "UTF-8");
            while (streamReader.ready()) {
                result.append((char) streamReader.read());
            }
            streamReader.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result.toString();
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static void writeToText(String str, String path) {
        try {
            // 生成的文件路径
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            // write 解决中文乱码问题
            // FileWriter fw = new FileWriter(file, true);
            OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.flush();
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeInfo(Map<String, String> map, String filePath) {
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath)), "UTF-8"));
            for (String name : map.keySet()) {
                bw.write(name + " " + map.get(name));
                bw.newLine();
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
